package controller

import (
	"GoTime/models"
	"GoTime/response"
	. "GoTime/utils"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"xorm.io/builder"
	"xorm.io/xorm"
)

func GetClassList(c *gin.Context) {
	var (
		classList []*response.ClassListResponse // 用于存储列表的响应
		err       error                         // 用于存储可能发生的错误
		page      int                           // 当前页码
		pageSize  int                           // 每页显示的记录数
		offset    int                           // 数据库查询时的偏移量
		count     int64                         // 场地列表的总记录数
	)

	// 检查请求中是否包含驾校ID参数
	if c.Query("school_id") == "" {
		// 如果驾校ID参数为空，返回错误信息
		c.JSON(http.StatusBadRequest, gin.H{"code": 201, "msg": "请选择驾校"})
		return
	}

	// 获取当前页码，默认为0
	page = cast.ToInt(c.DefaultQuery("page", "0"))
	// 获取每页显示的记录数，默认为10
	pageSize = cast.ToInt(c.DefaultQuery("pageSize", "10"))
	// 计算数据库查询的偏移量
	offset = (page - 1) * pageSize

	// 创建一个新的查询条件构建器
	filter := builder.NewCond()
	// 添加驾校ID的查询条件
	filter = filter.And(builder.Eq{"dc.school_id": c.Query("school_id")})

	// 如果请求中包含名称参数，则添加
	if phone := c.Query("class_name"); phone != "" {
		filter = filter.And(builder.Like{"dc.class_name", phone})
	}
	if trainingCarType := c.Query("training_car_type"); trainingCarType != "" {
		filter = filter.And(builder.Eq{"dc.training_car_type": trainingCarType})
	}
	classList, count, err = new(models.CharStandard).GetList(filter, pageSize, offset)

	// 如果发生错误，返回错误信息
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "获取班级列表失败", "data": err})
		return
	}

	// 如果成功，返回成功信息及数据
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "获取班级列表成功", "data": gin.H{"count": count, "list": classList}})
	return
}

func AddClass(c *gin.Context) {
	// 接收请求参数
	var (
		reqType int64
		url     string
		retMap  map[string]interface{}
	)
	class := new(models.CharStandard)
	if err := c.ShouldBind(&class); err != nil {
		log.Println(err)
		c.JSON(http.StatusBadRequest, gin.H{"code": 201, "msg": "参数错误"})
		return
	}
	ok, school, err := new(models.School).GetSchoolById(cast.ToInt(c.PostForm("school_id")))
	if err != nil || !ok {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "驾校不存在"})
		return
	}
	// 获取数据库引擎实例
	var engine = models.Engine
	// 创建一个新的数据库会话
	var session = engine.NewSession()
	// 确保在函数结束时关闭会话
	defer session.Close()

	// 开始一个数据库事务
	if err := session.Begin(); err != nil {
		// 如果事务开始失败，返回错误信息
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "事务开始失败"})
		return
	}
	class.SchoolId = school.Id
	class.TrainingTime = "9"
	class.UpdateTime = time.Now()
	class.Isused = "1"
	class.Appointments = "0"
	class.Zhouqi = 0
	if _, err := session.InsertOne(class); err != nil {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	//class.Record(school.InstitutionCode, class)
	log.Println(class)
	//备案收费标准
	data := map[string]interface{}{
		"inscode":       school.InstitutionCode,              //培训机构编号
		"seq":           class.Id,                            //收费标准编号
		"vehicletype":   class.TrainingCarType,               //培训车型
		"trainningmode": class.TrainingMode,                  //培训模式
		"trainningtime": class.TrainingTime,                  //培训时段
		"chargemode":    class.ChargeMode,                    //收费模式
		"paymode":       class.PayMode,                       //付费模式
		"price":         class.Price,                         //金额
		"classcurr":     class.ClassName,                     //班型名称
		"uptime":        class.UpdateTime.Format("20060102"), //更新时间
	}

	if url, err = GetSignURL("charStandard", data, reqType, school.Province, school.City); err != nil {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	var api_log models.ApiLog
	param, err := json.Marshal(data)
	api_log.Url = url
	api_log.Param = string(param)
	api_log.Method = "POST"
	api_log.Time = time.Now()
	if retMap, err = APIReq(url, data, "POST"); err != nil {
		result, _ := json.Marshal(retMap)
		api_log.Result = string(result)
		api_log.Add()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	result, _ := json.Marshal(retMap)
	api_log.Result = string(result)
	api_log.Add()
	fmt.Println(retMap)
	errorcode, _ := cast.ToFloat64E(retMap["errorcode"])
	if errorcode != 0 && !strings.Contains(retMap["message"].(string), "已经备案") {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": retMap["message"]})
		return
	}
	err = session.Commit()
	if err != nil {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "添加班级失败"})
		return
	}
	// 返回成功信息
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "添加班级成功"})
	return
}

func EditClass(c *gin.Context) {
	var (
		classId  string
		schoolId string
		//err      error
		url     string
		retMap  map[string]interface{}
		reqType int64
	)
	if classId = c.PostForm("class_id"); classId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"code": 201, "msg": "参数错误"})
		return
	}
	// 获取请求中的驾校ID参数
	if schoolId = c.PostForm("school_id"); schoolId == "" {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "缺少驾校ID"})
		return
	}

	// 查询指定驾校ID的驾校信息
	ok, school, err := new(models.School).GetSchoolById(cast.ToInt(schoolId))
	if err != nil || !ok {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询驾校信息失败"})
		return
	}
	standard, err := new(models.CharStandard).GetSignChatStandard(classId)
	if err != nil || standard.Id == 0 {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "班级不存在"})
		return
	}
	if err := c.ShouldBind(standard); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	var engine *xorm.Engine
	engine = models.Engine
	session := engine.NewSession()
	defer session.Close()
	data := map[string]interface{}{
		"inscode":       school.InstitutionCode,                 //培训机构编号
		"seq":           standard.Id,                            //收费标准编号
		"vehicletype":   standard.TrainingCarType,               //培训车型
		"trainningmode": standard.TrainingMode,                  //培训模式
		"trainningtime": standard.TrainingTime,                  //培训时段
		"chargemode":    standard.ChargeMode,                    //收费模式
		"paymode":       standard.PayMode,                       //付费模式
		"price":         standard.Price,                         //金额
		"classcurr":     standard.ClassName,                     //班型名称
		"uptime":        standard.UpdateTime.Format("20060102"), //更新时间
	}
	reqType = 2
	if url, err = GetSignURL("charStandard", data, reqType, school.Province, school.City); err != nil {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	var apiLog models.ApiLog
	param, err := json.Marshal(data)
	apiLog.Url = url
	apiLog.Param = string(param)
	apiLog.Method = "POST"
	apiLog.Time = time.Now()
	if retMap, err = APIReq(url, data, "POST"); err != nil {
		result, _ := json.Marshal(retMap)
		apiLog.Result = string(result)
		apiLog.Add()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	result, _ := json.Marshal(retMap)
	apiLog.Result = string(result)
	apiLog.Add()
	fmt.Println(retMap)
	errorcode, _ := cast.ToFloat64E(retMap["errorcode"])
	if errorcode != 0 {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": retMap["message"]})
		return
	}
	_, err = session.ID(standard.Id).Update(standard)
	if err != nil {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	err = session.Commit()
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "修改班级成功"})
	return
}

func DeleteClass(c *gin.Context) {
	// 接收请求参数
	var (
		classId  string
		schoolId string
		err      error
		url      string
		retMap   map[string]interface{}
		reqType  int64
	)
	if classId = c.Query("class_id"); classId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"code": 201, "msg": "参数错误"})
		return
	}
	// 获取请求中的驾校ID参数
	if schoolId = c.Query("school_id"); schoolId == "" {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "缺少驾校ID"})
		return
	}

	// 查询指定驾校ID的驾校信息
	ok, school, err := new(models.School).GetSchoolById(cast.ToInt(schoolId))
	if err != nil || !ok {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询驾校信息失败"})
		return
	}
	standard, err := new(models.CharStandard).GetSignChatStandard(classId)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	if school.City == "130100" {
		reqType = 3
	} else {
		reqType = 2
	}
	if url, err = GetSignURL(school.InstitutionCode+"-charStandard-"+cast.ToString(standard.Id), nil, reqType, school.Province, school.City); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	var api_log models.ApiLog
	api_log.Url = url
	api_log.Param = ""
	api_log.Method = "POST"
	api_log.Time = time.Now()
	if retMap, err = APIReq(url, nil, "DELETE"); err != nil {
		result, _ := json.Marshal(retMap)
		api_log.Result = string(result)
		api_log.Add()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	result, _ := json.Marshal(retMap)
	api_log.Result = string(result)
	api_log.Add()
	fmt.Println(retMap)
	errorcode, _ := cast.ToFloat64E(retMap["errorcode"])
	if errorcode != 0 && !strings.Contains(retMap["message"].(string), "已经备案") {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	// 获取数据库引擎实例
	var engine = models.Engine
	// 创建一个新的数据库会话
	var session = engine.NewSession()
	// 确保在函数结束时关闭会话
	defer session.Close()

	// 开始一个数据库事务
	if err := session.Begin(); err != nil {
		// 如果事务开始失败，返回错误信息
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "事务开始失败"})
		return
	}
	// 删除班级
	standard.Isused = "0"
	if _, err := session.ID(standard.Id).Cols("isused").Update(standard); err != nil {
		log.Println(err)
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "删除班级失败"})
		return
	}
	session.Commit()
	// 返回成功信息
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "删除班级成功"})
}
